package logger

import (
	"github.com/phachon/go-logger"
)

var log *go_logger.Logger

type LoggerConfig struct {
	//输出到哪里"console","file"
	Out string
	//输出的日志格式
	Formate string
	//是否输出Json格式，如果为true,则Formate可以不填
	JsonFormat bool
	//日志级别
	Level int
	//日志文件目录,只对为Out为file有效
	FilePath string
	//日志文件最大容量单位K,只对为Out为file有效
	MaxSize int64
	//日志文件最多行数,只对为Out为file有效
	MaxLine int64
	// 日志文件按照什么格式切分
	// "y" Log files are cut through year
	// "m" Log files are cut through mouth
	// "d" Log files are cut through day
	// "h" Log files are cut through hour
	DateSlice string
}

var ConsoleConfig = LoggerConfig{
	Out:"console",
	Formate: "%millisecond_format%-[%file%:%line%]:%body%",
	JsonFormat:false,
	Level:go_logger.LOGGER_LEVEL_DEBUG,
}

var FileConfig = LoggerConfig{
	Out:"file",
	Formate: "%millisecond_format%-[%file%:%line%]:%body%",
	JsonFormat:false,
	Level:go_logger.LOGGER_LEVEL_DEBUG,
	FilePath:"log.log",
	MaxSize:1024 * 1024,
	MaxLine:10000,
	DateSlice:"d",
}

var loggerConfigs []LoggerConfig

func AddConfig(config LoggerConfig){
	loggerConfigs = append(loggerConfigs, config)
}

func NewLogger() (logger *go_logger.Logger){
	//初始化日志
	AddConfig(FileConfig)
	AddConfig(ConsoleConfig)
	log := go_logger.NewLogger()
	log.Detach("console")

	for _, config := range loggerConfigs{
		var logConfig go_logger.Config
		if "console" == config.Out {
			logConfig = &go_logger.ConsoleConfig{
				Color: false,
				JsonFormat: config.JsonFormat,
				Format: config.Formate,
			}
		}else if "file" == config.Out {
			logConfig = &go_logger.FileConfig{
				Filename: config.FilePath,
				JsonFormat: config.JsonFormat,
				Format: config.Formate,
				DateSlice: config.DateSlice,
				MaxLine: config.MaxLine,
				MaxSize : config.MaxSize,
			}
		}
		log.Attach(config.Out, go_logger.LOGGER_LEVEL_DEBUG, logConfig)
	}
	return log
}

func getLog() *go_logger.Logger {
	if log == nil {
		log = NewLogger()
	}
	return log
}

func Error(msg string){
	getLog().Error(msg)
}

func Errorf(formate string, s ...interface{}){
	getLog().Errorf(formate, s)
}

func Info(msg string){
	getLog().Info(msg)
}

func Infof(formate string, s ...interface{}){
	getLog().Infof(formate, s)
}

func Debug(msg string){
	getLog().Debug(msg)
}

func Debugf(formate string, s ...interface{}){
	getLog().Debugf(formate, s)
}

func Warning(msg string){
	getLog().Warning(msg)
}

func Warningf(formate string, s ...interface{}){
	getLog().Warningf(formate, s)
}